use axum::{extract::Multipart, response::IntoResponse};
use http::StatusCode;
use shq_excel_report::import_excel_by_bytes;
pub async fn upload_excel_and_import(mut multipart: Multipart) -> impl IntoResponse {
    let mut field = match multipart.next_field().await {
        Ok(Some(field)) => field,
        Ok(None) => return Err((StatusCode::BAD_REQUEST, "没有提交文件".to_string())),
        Err(err) => {
            log::error!("读取文件字段失败: {:?}", err);
            return Err((StatusCode::INTERNAL_SERVER_ERROR,
                format!("读取上传文件失败: {}", err)));
        }
    };
    // 获取文件名
    let fname = field.file_name().unwrap_or("").to_string();
    if fname.is_empty() {
        return Err((StatusCode::BAD_REQUEST, "请选择要上传的文件".to_string()));
    }
    // 检查文件扩展名
    if !fname.to_lowercase().ends_with(".xlsx") && !fname.to_lowercase().ends_with(".xls") {
        return Err((StatusCode::BAD_REQUEST,
            "请上传Excel文件(.xlsx或.xls格式)".to_string()));
    }
    // 设置最大文件大小限制 (10MB)
    const MAX_FILE_SIZE: usize = 10 * 1024 * 1024;
    // 创建缓冲区存储所有数据块
    let mut bytes = Vec::new();
    let mut total_size = 0;
    // 分块读取文件内容
    loop {
        let chunk_result = field.chunk().await;
        match chunk_result {
            Ok(chunk) => {
                if chunk.is_none() {
                    break;
                }
                let chunk = chunk.unwrap();
                let chunk_size = chunk.len();
                total_size += chunk_size;
                // 检查文件大小限制
                if total_size > MAX_FILE_SIZE {
                    return Err((
                        StatusCode::PAYLOAD_TOO_LARGE,
                        format!("文件过大，最大允许10MB，当前文件大小{}MB",
                               total_size / 1024 / 1024),
                    ));
                }
                // 将数据块添加到缓冲区
                bytes.extend_from_slice(&chunk);
            }
            Err(err) => {
                log::error!("读取文件块失败: {:?}", err);
                return Err((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    format!("读取文件内容失败: {}", err),
                ));
            }
        }
    }
    // 处理Excel导入
    match import_excel_by_bytes(bytes, &fname).await {
        Ok(_) => {
            Ok(())
        }
        Err(err) => {
            log::error!("导入失败: {:?}", err);
            Err((StatusCode::BAD_REQUEST, format!("导入失败: {}", err)))
        }
    }
}